package uia.alumni.profile;

import java.io.IOException;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.transaction.UserTransaction;
import uia.alumni.data.Role;
import uia.alumni.data.User;
import uia.alumni.web.Command;



/**
 * Process the EditPassword form. If everything is ok the new
 * password is saved and the ViewProfile page is displayed.
 * Otherwise the EditPassword form is redisplayed with an error
 * message explaining the problem.
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class SavePassword  extends Command implements Constants {
    /** SERVLET_NAME is used for consistency checking of web.xml */
    public static final String SERVLET_NAME = "profile.savepassword";

    @PersistenceUnit(name=PERSISTENCE_UNIT)
    private EntityManagerFactory emf;

    @Resource
    private UserTransaction tx;


    public SavePassword() {
        super(Role.member);
    }


    /**
     * Save the password from the EditPassword form, IF THE OLD PASSWORD
     * IS CORRECT.
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    public void execute(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        boolean success = false;

        try {
            tx.begin();
            EntityManager em = emf.createEntityManager();
            User user = getLoggedInUser(em, request);
            String oldPwd = request.getParameter(OLDPASSWORD);
            String[] newPwd = request.getParameterValues(PASSWORD);

            if (! user.getPassword().equals(oldPwd))
                throw new Exception("Old password is wrong!");
            if (newPwd.length != 2)
                throw new Exception("New password not entered twice!");
            if (! newPwd[0].equals(newPwd[1]))
                throw new Exception("Confirmation does not match new password!");

            user.setPassword(newPwd[0]);
            success = true;
            addMessage(request, "Password changed!");
            tx.commit();
        }
        catch(Exception e) {
            addMessage(request, "Password not changed, because: "+e.getMessage());
        }

        if (success) forwardTo(ViewProfile.SERVLET_NAME, request, response);
        else forwardTo(EditPassword.SERVLET_NAME, request, response);
    }

    public final static long serialVersionUID = 1;

}
